package com.mzw.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzw.project.common.BaseResponse;
import com.mzw.project.common.ResultUtils;
import com.mzw.project.model.entity.SeckillVoucher;
import com.mzw.project.model.entity.Voucher;
import com.mzw.project.service.SeckillVoucherService;
import com.mzw.project.service.VoucherService;
import com.mzw.project.mapper.VoucherMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author L1nAn
 * @description 针对表【voucher】的数据库操作Service实现
 * @createDate 2023-09-17 11:39:48
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher>
        implements VoucherService {


    @Resource
    private SeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public BaseResponse<List<Voucher>> queryVoucherOfShop(Long interfaceInfoId) {
        // 查询抵用券信息
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(interfaceInfoId);
        // 返回结果
        return ResultUtils.success(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        // 将秒杀优惠券库存入redis中
        stringRedisTemplate.opsForValue().set("seckill:stock:" + voucher.getId(), voucher.getStock().toString());
    }
}




